package com.nuckly.news.ui.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.nuckly.news.data.ResultWrapper
import com.nuckly.news.databinding.FragmentNewsFeedBinding
import com.nuckly.news.ui.activity.NewsActivity
import com.nuckly.news.ui.adapter.NewsFeedAdapter
import com.nuckly.news.ui.viewmodel.NewsFeedViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class NewsFeedFragment : Fragment() {

    private var _binding: FragmentNewsFeedBinding? = null
    private val binding get() = _binding

    private val newsFeedViewModel by viewModels<NewsFeedViewModel>()
    private lateinit var adapter: NewsFeedAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentNewsFeedBinding.inflate(layoutInflater)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initAdapter()
        loadNewsFeeds()
    }

    private fun initAdapter() {
        adapter = NewsFeedAdapter { news ->
            NewsActivity.startActivity(requireActivity(), news)
        }
        binding?.newsFeedRecyclerView?.adapter = adapter
    }

    private fun loadNewsFeeds() {
        newsFeedViewModel.getNewsFeeds().observe(viewLifecycleOwner) {
            when (it) {
                is ResultWrapper.Loading -> {
                }
                is ResultWrapper.Success -> {
                    adapter.submitList(it.data)
                }
                is ResultWrapper.Error -> {
                    it.message?.apply {
                        Log.e(TAG, it.message)
                    }
                }
            }
        }
    }

    companion object {

        const val TAG = "NewsFeedFragment"

        fun newIntent() = NewsFeedFragment()
    }

}